import globalApi from '@/api/GlobalApi'
import router, { isEncryptRouter, dynamicRouters, encryptRouters, filterDynamicRouters } from '@/router/index'
import { acceptHMRUpdate, defineStore } from 'pinia'

const defaultPermissions: Array<string> = [
    'monitoringCenter'
]

const useBasicStore = defineStore({
    id: 'basic',
    state:() => {
        return {
            // 用户信息
            userDetail: <{ url?: string } | any>{},
            // 路由权限
            permissions: <string | any>[],
            // 菜单信息
            menus: <any>[],
            // 近5次面包屑
            currentRouters: <{} | any>[]
        }
    },
    getters: {
        // TODO
    },
    actions: {
        registerUser (user: {} | any) {
            this.userDetail = user
        },
        deregisterUser() {
            this.userDetail = void 0
        },
        initPermissions(list: [string]) {
            this.permissions = list
        },
        initMenus(list: [{} | any]) {
            this.menus = list
        },
        updateCurrentRouters(router: {} | any) {
            this.currentRouters.push(router)
            if (this.currentRouters.length > 5) this.currentRouters = this.currentRouters.slice(this.currentRouters.length - 5)
        },
        initPermissionList(args: {} | any) {
            // 权限加载 -> 默认或通过接口获取
            globalApi.systemApi.queryUserMenu(args).then((r: any) => {
                // TODO 需要写入真正得权限
                r = r ?? defaultPermissions
                r = [ 'back', ...r ]
                this.$patch(state => state.permissions = r)
                let f = filterDynamicRouters(dynamicRouters, r)
                if (isEncryptRouter) f = encryptRouters(f)
                // console.log(router.getRoutes())
                f.forEach(m => {
                    router.addRoute(m)
                })
                // 神奇！注意路由数量得变化！
                // console.log(router.getRoutes())
                this.$patch(state => state.menus = f)
            })
        }
    },
    persist: {
        // https://prazdevs.github.io/pinia-plugin-persistedstate/guide/
        storage: sessionStorage
    }
})

if (import.meta.hot) {
    import.meta.hot.accept(acceptHMRUpdate(useBasicStore, import.meta.hot))
}

export default useBasicStore
